package cn.edu.baiyunu.myapplication.ui.screens.profile

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import cn.edu.baiyunu.myapplication.data.model.SavingsGoal
import cn.edu.baiyunu.myapplication.ui.components.GlassmorphismCard
import cn.edu.baiyunu.myapplication.ui.screens.profile.viewmodel.ProfileViewModel
import cn.edu.baiyunu.myapplication.ui.theme.gradientBackground
import cn.edu.baiyunu.myapplication.ui.utils.IconUtils

/**
 * 储蓄目标界面
 */
@Composable
fun SavingsGoalScreen(
    onBackClick: () -> Unit,
    viewModel: ProfileViewModel = hiltViewModel()
) {
    // 获取UI状态
    val profileUiState by viewModel.profileUiState.collectAsState()
    
    // 弹窗状态
    var showAddDialog by remember { mutableStateOf(false) }
    var showEditDialog by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    
    // 当前编辑/删除的目标
    var currentGoal by remember { mutableStateOf<SavingsGoal?>(null) }
    
    // 创建背景渐变
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(gradientBackground)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .statusBarsPadding()
                .padding(16.dp)
        ) {
            // 顶部栏
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 返回按钮
                IconButton(
                    onClick = onBackClick,
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(Color.White.copy(alpha = 0.2f))
                ) {
                    Icon(
                        imageVector = Icons.Filled.ArrowBack,
                        contentDescription = "返回",
                        tint = Color.White
                    )
                }
                
                // 标题
                Text(
                    text = "储蓄目标管理",
                    modifier = Modifier
                        .weight(1f)
                        .padding(start = 16.dp),
                    color = Color.White,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold
                )
                
                // 添加按钮
                IconButton(
                    onClick = { showAddDialog = true },
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(Color.White.copy(alpha = 0.2f))
                ) {
                    Icon(
                        imageVector = Icons.Filled.Add,
                        contentDescription = "添加",
                        tint = Color.White
                    )
                }
            }
            
            // 储蓄目标列表
            if (profileUiState.savingsGoals.isEmpty()) {
                // 空状态
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "暂无储蓄目标",
                            color = Color.White.copy(alpha = 0.7f),
                            fontSize = 18.sp
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Button(
                            onClick = { showAddDialog = true },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color.White.copy(alpha = 0.2f)
                            )
                        ) {
                            Text("添加目标")
                        }
                    }
                }
            } else {
                // 显示列表
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .weight(1f),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    items(profileUiState.savingsGoals) { goal ->
                        SavingsGoalItem(
                            goal = goal,
                            onEdit = {
                                currentGoal = goal
                                showEditDialog = true
                            },
                            onDelete = {
                                currentGoal = goal
                                showDeleteDialog = true
                            }
                        )
                    }
                    // 底部间距
                    item { 
                        Spacer(modifier = Modifier.height(80.dp))
                    }
                }
            }
        }
        
        // 添加目标对话框
        if (showAddDialog) {
            SavingsGoalDialog(
                goal = null,
                onDismiss = { showAddDialog = false },
                onSave = { name, targetAmount, savingRate, icon, type ->
                    viewModel.addSavingsGoal(
                        name = name,
                        targetAmount = targetAmount,
                        savingRate = savingRate,
                        icon = icon,
                        type = type
                    )
                    showAddDialog = false
                }
            )
        }
        
        // 编辑目标对话框
        if (showEditDialog && currentGoal != null) {
            SavingsGoalDialog(
                goal = currentGoal,
                onDismiss = { showEditDialog = false },
                onSave = { name, targetAmount, savingRate, icon, type ->
                    currentGoal?.id?.let { goalId ->
                        viewModel.updateSavingsGoal(
                            goalId = goalId,
                            name = name,
                            targetAmount = targetAmount,
                            savingRate = savingRate,
                            icon = icon,
                            type = type
                        )
                    }
                    showEditDialog = false
                }
            )
        }
        
        // 删除确认对话框
        if (showDeleteDialog && currentGoal != null) {
            AlertDialog(
                onDismissRequest = { showDeleteDialog = false },
                title = { Text("删除储蓄目标") },
                text = { Text("确定要删除「${currentGoal?.name}」这个储蓄目标吗？") },
                containerColor = Color(0xFF2A2A2A),
                titleContentColor = Color.White,
                textContentColor = Color.White.copy(alpha = 0.8f),
                confirmButton = {
                    TextButton(
                        onClick = {
                            currentGoal?.id?.let { viewModel.deleteSavingsGoal(it) }
                            showDeleteDialog = false
                        }
                    ) {
                        Text("删除", color = Color(0xFFFF5252))
                    }
                },
                dismissButton = {
                    TextButton(
                        onClick = { showDeleteDialog = false }
                    ) {
                        Text("取消", color = Color.White.copy(alpha = 0.8f))
                    }
                }
            )
        }
    }
}

/**
 * 储蓄目标项
 */
@Composable
fun SavingsGoalItem(
    goal: SavingsGoal,
    onEdit: () -> Unit,
    onDelete: () -> Unit
) {
    GlassmorphismCard(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // 顶部：标题和图标
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 图标
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(Color.White.copy(alpha = 0.2f)),
                    contentAlignment = Alignment.Center
                ) {
                    val icon = IconUtils.getIconByName(goal.icon)
                    Icon(
                        imageVector = icon,
                        contentDescription = goal.name,
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
                
                // 标题和类型
                Column(
                    modifier = Modifier
                        .weight(1f)
                        .padding(start = 16.dp)
                ) {
                    Text(
                        text = goal.name,
                        color = Color.White,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Text(
                        text = when(goal.type) {
                            "short" -> "短期目标"
                            "medium" -> "中期目标"
                            "long" -> "长期目标"
                            else -> "目标"
                        },
                        color = Color.White.copy(alpha = 0.7f),
                        fontSize = 12.sp
                    )
                }
                
                // 操作按钮
                Row(
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier
                            .size(32.dp)
                            .clip(CircleShape)
                            .background(Color.White.copy(alpha = 0.1f))
                            .clickable(onClick = onEdit),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Edit,
                            contentDescription = "编辑",
                            tint = Color.White.copy(alpha = 0.8f),
                            modifier = Modifier.size(16.dp)
                        )
                    }
                    
                    Box(
                        modifier = Modifier
                            .size(32.dp)
                            .clip(CircleShape)
                            .background(Color(0xFFFF5252).copy(alpha = 0.2f))
                            .clickable(onClick = onDelete),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Delete,
                            contentDescription = "删除",
                            tint = Color(0xFFFF5252),
                            modifier = Modifier.size(16.dp)
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 目标信息
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                // 目标金额
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "目标金额",
                        color = Color.White.copy(alpha = 0.7f),
                        fontSize = 12.sp
                    )
                    
                    Text(
                        text = "¥${goal.targetAmount}",
                        color = Color.White,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
                
                // 储蓄率
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "储蓄率",
                        color = Color.White.copy(alpha = 0.7f),
                        fontSize = 12.sp
                    )
                    
                    Text(
                        text = "${goal.savingRate}%",
                        color = Color.White,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
                
                // 预计完成
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "估计时间",
                        color = Color.White.copy(alpha = 0.7f),
                        fontSize = 12.sp
                    )
                    
                    // 简单估算：按每月收入的储蓄率计算
                    val monthlyIncome = 5000.0 // 假设
                    val monthlySaving = monthlyIncome * (goal.savingRate / 100)
                    val months = if (monthlySaving > 0) (goal.targetAmount / monthlySaving).toInt() else 0
                    
                    Text(
                        text = if (months > 0) "$months 个月" else "计算中",
                        color = Color.White,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }
    }
} 